﻿/**
 * ChelloTraffic widget
 * (C) 2006-2007, Sebestyén Gábor
 *
 * Project Home: http://code.google.com/p/chellotraffic/
 */

var CTWebClient = function(uname, pwd) {
    this.state = 0;
    this.loggedIn = false;
    this.userName = uname;
    this.password = pwd;
};


CTWebClient.prototype = {
    getHTTPClient: function() {
        var xmlhttp;

        if (window.ActiveXObject) {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
    	    xmlhttp = new XMLHttpRequest();
        }
        return xmlhttp;
    },



    start: function() {
        var self = this;
        this.xmlhttp = this.getHTTPClient();

        this.xmlhttp.open("POST", "https://kezeles.chello.hu/index.php");
        this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        this.xmlhttp.onreadystatechange = function() {
	        if (self.xmlhttp.readyState==4) {
		        if (self.xmlhttp.status==200) {
                    // debug
                    // alert("start[2.11] COOKIE <" + self.xmlhttp.getResponseHeader("Set-Cookie") + ">");
                    // alert("start[2.12] TXT " + self.xmlhttp.responseText);
                    // alert("start[2.13] XML " + self.xmlhttp.responseXML);
                    // alert("start[2.13] OK ");
                    // alert("start[2.14] HDRS: " + self.xmlhttp.getAllResponseHeaders());

                    if (/\<font\sclass='error'\>/.test(self.xmlhttp.responseText)) {
                        // alert("start[2.12] TXT " + self.xmlhttp.responseText);
		                self.handleError(2, "CTWebClient: LOGIN FAILED");
                    } else if (/Adatforgalom/.test(self.xmlhttp.responseText)) {
		                // call phase 2
		                self.state = 2;
		                self.loggedIn = true;
   		                self.getData();
                    } else {
		                self.handleError(2, "CTWebClient: LOGIN FAILED");
                    }
		        } else if (self.xmlhttp.status==12019) {
		            // Certificate of kezeles.chello.hu is not trusted
		            // Solution: import that certificate to your Trusted Certificates
	                self.handleError(3, "CTWebClient: CERT ERROR");
	                self.handleCommError(self.xmlhttp);
		        } else {
	                self.handleError(2, "CTWebClient: COMM ERROR " + self.xmlhttp.status + "/" + self.xmlhttp.statusText);
	                self.handleCommError(self.xmlhttp);
		        }
	        }
        };
	    this.xmlhttp.send("userName=" + escape(this.userName) + "&passWord=" + escape(this.password) );
    },



    getData: function() {
        if (this.state != 2 && !this.loggedIn) {
            this.state = -1;
            this.err = 1;
            /// alert("CTWebClient.getData(): not logged in, bye");
            return;
        }
    
        var self = this;
        this.xmlhttp = this.getHTTPClient();

        // get current month data
        this.xmlhttp.open("GET", "https://kezeles.chello.hu/stat.php?type=cur");
        // this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	    this.xmlhttp.onreadystatechange = function() {
		    if (self.xmlhttp.readyState==4) {
			    if (self.xmlhttp.status==200) {
			        self.state = 3;
			        // do process ...
			        self.processCurrentData(self.xmlhttp);

			        self.state = 4;
			        self.logout();
			    } else {
			        /// alert("CTWebClient: GENERAL FAILURE");
	                self.handleCommError(self.xmlhttp);
			    }
		    }
	    };
	    this.xmlhttp.send();
    },


    logout: function() {
        if (this.state == -1 || !this.loggedIn) {
            /// alert("CTWebClient.logout(): not logged in, bye");
            return;
        }
        // ...
        var self = this;
        this.xmlhttp = this.getHTTPClient();

        this.xmlhttp.open("POST", "https://kezeles.chello.hu/index.php");
        this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        this.xmlhttp.onreadystatechange = function(){
 		    if (self.xmlhttp.readyState==4) {
			    if (self.xmlhttp.status==200) {
                    self.xmlhttp.state = 4; // logged out!
                    self.loggedIn = -1;
                    alert("LOGGED OUT");
                    
                    // TODO: send event on ending process?
                } else {
	                self.handleCommError(self.xmlhttp);
                }
            }
        };
        this.xmlhttp.send("logOut=1");
    },



    monthlyDataRe: /\<img\ssrc=\'images\/\d\.gif\'[^a]+alt\=\'([a-zA-Z&;]+):\s([0-9\s]+)\sMB\'\>/,
    processCurrentData: function(transport) {
        var t = transport.responseText;
        var curM = 0;
        
        if(/<strong>Hiba<\/strong>/.test(t)) {
            /// alert("CTWebClient.processCurrentData(): invalid data / 'hiba'");
            this.handleError(1, "invalid data / 'hiba'"); // general error
            return;
        }
        
        if (/^\s+Nincs\sadat\./.test(t)) {
            /// alert("CTWebClient.processCurrentData(): no data");
            curM = 0;
        } else {
            var m = /([0-9\s]+)\sMB/.exec(t);
            if (m) {
                var val =  m[1].replace(/\s/g, "");
                curM = Number(val);
            } else {
                m = /^\s+MB\s/.exec(t);
                if (m) {
                    curM = 0;
                } else {
                    // error?
                }
            }
        }
        
        if (typeof(this.onsuccess) == "function") {
            this.onsuccess(this, {
                currentMonth: curM
            });
        }
    },


    handleCommError: function(transport) {
        // debug
        /// alert("CTWebClient.handleCommError");

        var err_msg = "Status: [" + transport.status + "] " + transport.statusText;
        this.handleError(3, err_msg);
    },

    handleError: function(err, message) {
        this.state = -1;
        this.err = err;
        /***
        if (message)
            alert("CTWebClient.handleError(" + err + ") called; " + message);
        else
            alert("CTWebClient.handleError(" + err + ") called");
        ***/
        if (typeof(this.onerror) == "function") {
            this.onerror(this, err, message);
        }
    }
};
